import random
from PIL import Image, ImageFont, ImageDraw
from io import BytesIO
from tornado import concurrent


def _random_color():
    """
    生成随机颜色
    :return:
    """
    return random.randint(0, 255), random.randint(10, 255), random.randint(64, 255)


def _random_char():
    random_num = str(random.randint(0, 9))  # 随机数字
    random_lower = chr(random.randint(65, 90))  # 随机小写字母
    random_upper = chr(random.randint(97, 122))  # 随机小写字母
    return random.choice([random_num, random_lower, random_upper])  # 随机选择


@concurrent.run_on_executor
def generate(self, length=4, width=130, height=46, font_size=40):
    img = Image.new(mode="RGB", size=(width, height), color="white")
    draw = ImageDraw.Draw(img, "RGB")
    font = ImageFont.truetype("util/kumo.ttf", font_size)  # 指定字体样式和大小
    valid_list = []
    # 生成length位数的随机字符
    for i in range(length):
        random_char = _random_char()
        draw.text([5 + i * 24, 10], random_char, _random_color(), font=font)
        # 这里列表里的两个参数表示横纵坐标，在img里面的,第二个参数表示文本内容，第三个是颜色，第四个是字体
        valid_list.append(random_char)
    # 加噪点
    for i in range(100):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=_random_color())
    # 加干扰线,这里通过添加多组横纵坐标实现
    for i in range(5):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)
        x3 = random.randint(0, width)
        y3 = random.randint(0, height)
        draw.line((x1, y1, x2, y2, x3, y3), fill=_random_color())

    f = BytesIO()  # 相当于获取文件句柄
    img.save(f, "png")  # 存入内存，以png的格式
    data = f.getvalue()  # 从内存中取出来
    valid_str = "".join(valid_list)  # 转化成随机的字符串格式
    return valid_str.upper(), data
